package com.vf.cloud.paas.app.master.api.sys.controller;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.app.master.api.sys.service.IUser;
import com.vf.cloud.paas.app.master.common.domain.User;
import com.vf.cloud.paas.app.master.common.vo.user.UserPasswordP;
import com.vf.cloud.paas.common.constant.SecurityConstant;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.log.annotation.RLog;
import com.vf.cloud.paas.common.security.annotation.TokenRequired;
import com.vf.cloud.paas.common.service.IRedis;
import com.vf.cloud.paas.common.util.EncryptUtil;
import com.vf.cloud.paas.common.util.JWTUtil;
import com.vf.cloud.paas.common.util.R;
import com.vf.cloud.paas.common.util.RsaUtil;
import com.vf.cloud.paas.common.util.UuidUtil;
import com.vf.cloud.paas.common.util.WebUtils;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/user")
public class UserController {

	@Autowired
	private IUser userImpl;
	@Autowired
	private IRedis redisImpl;
	
	@RLog(value = "获取用户树列表", type = "user")
	@TokenRequired
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public R<List<User>> list(HttpServletRequest request,@RequestBody User param) {
		User user = WebUtils.getCurUser(request);
		if (user == null) {
			return R.expired();
		}
		if (StrKit.equals("admin", user.getRoleMark())) {
			param.setId("-1");
		}else {
			param.setId(user.getId());
		}
		return R.ok(userImpl.list(param));
	}

	@RLog(value = "获取用户信息", type = "user")
	@TokenRequired
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public R<User> info(HttpServletRequest request) {
		try {
			String token = request.getHeader(SecurityConstant.HEADER);
			token = token.replace(SecurityConstant.TOKEN_SPLIT, "");
			String userId = JWTUtil.getClainByName(token, "userId").asString();

			User user = User.dao.findById(userId);
			if (!StrKit.isBlank(user.getRoleMark())) {
				String[] roles = user.getRoleMark().split(",");
				user.setRoles(roles);
			}
			List<String> perms=new LinkedList<String>();
			
			if(StrKit.equals(user.getRoleMark(),"admin")) {
				perms.add("admin:add");
			}
			else if(StrKit.equals(user.getRoleMark(),"group")) {
				perms.add("group:add");
			}
			user.setPerms(perms);
			user.setPassword("");
			return R.ok(user);
		} catch (Exception e) {
			return R.failed(10042, "会话过期，请重新登录！");
		}
	}

	
	@RequestMapping(value = "TokenExpired", method = RequestMethod.GET)
	public R<String> TokenExpired(HttpServletRequest request) {
		return R.failed(10042, "会话过期，请重新登录！");
	}

	@RLog(value = "保存用户", type = "user")
	@TokenRequired
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<User> save(@RequestBody User param) {
		if (StrKit.isBlank(param.getId())) {
			param.setId(UuidUtil.getUUID());
			param.setPassword(EncryptUtil.encrypt("rs@123"));
			if (StrKit.isBlank(param.getPid())) {
				param.setPid("-1");
				param.setRoleMark("group");
			}
			if (param.save())
				return R.ok();
		}
		if (param.update())
			return R.ok();
		return R.failed();
	}
	
	@RLog(value = "重置用户密码", type = "user")
	@TokenRequired
	@RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
	public R<User> resetPwd(@RequestBody User param) {
		param.setPassword(EncryptUtil.encrypt("rs@123"));
		if (param.update())
			return R.ok();
		return R.failed();
	}

	@RLog(value = "修改用户密码", type = "user")
	@TokenRequired
	@Tx
	@RequestMapping(value = "/password", method = RequestMethod.POST)
	public R<User> password(HttpServletRequest request,@RequestBody UserPasswordP userPassword) {
		try {
			if (userPassword == null || StrKit.isBlank(userPassword.getOldPassword()) || StrKit.isBlank(userPassword.getNewPassword())) {
				return R.failed("参数必填.");
			}

			String oldPwd = "";
			String newPwd = "";
			try {
				oldPwd = RsaUtil.decrypt(userPassword.getOldPassword(), SecurityConstant.PRIVATE_KEY);
				newPwd = RsaUtil.decrypt(userPassword.getNewPassword(), SecurityConstant.PRIVATE_KEY);
			} catch (Exception e) {
				e.printStackTrace();
				return R.failed("解密信息失败!");
			}

			User user = User.dao.findById(request.getAttribute("currentUserId"));
			if (user == null) {
				return R.failed("用户不存在.");
			}

			if (EncryptUtil.matches(oldPwd, user.getPassword())) {
				return R.failed("原始密码错误.");
			}

			user.setPassword(EncryptUtil.encrypt(newPwd));
			if (user.update()) {
				String token = request.getHeader(SecurityConstant.HEADER);
				token = token.replace(SecurityConstant.TOKEN_SPLIT, "");
				redisImpl.delete(token);
				return R.failed("成功.");
			} else {
				return R.failed("失败.");
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RLog(value = "删除用户", type = "user")
	@TokenRequired
	@Tx
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public R<String> delete(@RequestBody User user) {
		if(userImpl.delete(user)) return R.ok();
		return R.failed();
	}

}
